<?php

namespace App\Service\ChatGroup;

use App\Enums\Common\NsqEnum;
use App\Enums\Mqtt\MqttEnum;
use App\Library\Rms\RmsUserApi;
use App\Models\BaseModel;
use App\Models\ChatGroup\ChatGroupFAQModel;
use App\Models\ChatGroup\ChatGroupHistoryModel;
use App\Models\ChatGroup\ChatGroupModel;
use App\Models\ChatGroup\ChatGroupSessionModel;
use App\Models\ChatGroup\ChatGroupUserModel;
use App\Models\Shop\ShopModel;
use App\Service\BaseService;
use App\Service\Rms\ShopService;
use Exception;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Kuafu\GreenContent\Content\TextContent;
use Kuafu\Nsq\NsqPublisher;

class ChatGroupStructService
{
    const QUEUE_NAME = '{chat-group}';

    /**
     * 群聊id
     * @var int
     */
    private int $groupId;

    /**
     * 门店id
     * @var int
     */
    private int $shopId;

    /**_
     * 推送结构体
     * @var array
     */
    private array $struct;

    /**
     * 推送得消息名称
     * @var string
     */
    private string $cmd;

    public function __construct(int $groupId, int $shopId = 0)
    {
        $this->groupId = $groupId;

        if (!$shopId) {
            $shopId = Cache::remember('ChatGroupStructService_shopId:' . $groupId, 3600, function () {
                return (int)ChatGroupModel::query()->where('id', $this->groupId)->value('shopId');
            });
        }

        $this->shopId = $shopId;
    }

    /**
     * 群聊消息结构体
     * @param int $currentUid 当前用户id
     * @param string $clientMsgId 客户端自己生成的id
     * @param string $type text/images/faq/tips
     * @param mixed $content 消息内容
     * @param int $faqId 常见问题id
     * @param int $sessionId 会话id
     * @param int $isSendAi 是否发送AI
     * @return $this
     * @throws Exception
     */
    public function sendMsgStruct(
        int $currentUid,
        string $clientMsgId,
        string $type,
        $content,
        int $faqId = 0,
        int $sessionId = 0,
        int $isSendAi = ChatGroupHistoryModel::IS_SEND_AI_NO,
        int $isRecordStatistics = ChatGroupHistoryModel::IS_RECORD_COUNT_YES
    ): self {
        // 消息结构体
        $this->struct = (new ChatGroupPrepareStructService($this->groupId, $this->shopId, $currentUid, $clientMsgId,
            $type, $content, $faqId, $sessionId, $isSendAi, $isRecordStatistics))->prepareStruct();

        $this->cmd = 'chatGroupMsgSend';

        return $this;
    }

    /**
     * 群聊消息撤回结构体
     * @param int $msgId
     * @return $this
     */
    public function recallMsgStruct(int $msgId): self
    {
        $this->struct = [
            'groupId' => $this->groupId,
            'msgId'   => $msgId,
        ];

        $this->cmd = 'chatGroupMsgRecall';

        return $this;
    }

    /**
     * 会话变化
     * @param ChatGroupSessionModel $groupSessionModel
     * @return $this
     */
    public function sessionChange(ChatGroupSessionModel $groupSessionModel)
    {
        $this->struct = [
            'groupId'   => $groupSessionModel->groupId,
            'sessionId' => $groupSessionModel->id,
            'robotIn'   => $groupSessionModel->robotIn,
            'serveIn'   => $groupSessionModel->serveIn,
            'serveUid'  => $groupSessionModel->serveUid,
            'serveName' => $groupSessionModel->serveName,
            'status'    => $groupSessionModel->status,
        ];

        $this->cmd = 'sessionChange';

        return $this;
    }

    /**
     * AI 思考中的状态
     *
     * @param ChatGroupSessionModel $groupSessionModel
     * @param int $isThink 1 思考中 0 没思考
     * @return $this
     */
    public function aiInThinking(ChatGroupSessionModel $groupSessionModel, int $isThink = 1): self
    {
        $robotInfo = ChatGroupUserModel::query()
                                       ->where('groupId', $groupSessionModel->groupId)
                                       ->where('userId', ChatGroupUserModel::KUA_XIAO_FU_USER_ID)
                                       ->first();

        if (empty($robotInfo)) {
            $this->struct = [];
            return $this;
        }

        $this->struct = [
            'shopId'      => $groupSessionModel->shopId,
            'groupId'     => $groupSessionModel->groupId,
            'isThink'     => $isThink,
            'user'        => [
                'id'     => $robotInfo->userId,
                'name'   => $robotInfo->alias,
                'avatar' => $robotInfo->avatar,
            ],
            'displayTime' => 10,
            'text'        => '夸小父正在思考中，请稍候~'
        ];

        $this->cmd = 'aiThinkStatus';

        return $this;
    }

    /**
     * 群组列表 - 置顶消息
     * @param ChatGroupSessionModel $groupSessionModel
     * @return $this
     */
    public function groupListsTopGroup(ChatGroupSessionModel $groupSessionModel): self
    {
        $shop = ShopModel::getDataById($this->shopId);

        $this->struct = [
            'shopId'      => $groupSessionModel->shopId,
            'groupId'     => $groupSessionModel->groupId,
            'name'        => ChatGroupModel::query()->where('id', $this->groupId)->value('name'),
            'groupAvatar' => 'https://file.51kuafu.com/5e/e8/07579232ee7a6d8e91a35752400830789d3bcd8ec874569b4124f1d2028f.jpeg',
            'shopCode'    => $shop->shopCode ?? '',
            'shopStatus'  => $shop->status ?? 0,
            'shopName'    => $shop->name ?? '',
            'lastMsgTime' => $groupSessionModel->lastMsgTime,
            "serveIn"     => $groupSessionModel->serveIn,
        ];

        $this->shopId = 0;
        $this->cmd    = 'groupListsTopGroup';

        return $this;
    }

    /**
     * 群聊tab数量
     * @return $this
     */
    public function groupTabNum(): self
    {
        foreach (
            [
                ChatGroupSessionModel::SERVE_IN_YES,
                ChatGroupSessionModel::SERVE_IN_ING,
                ChatGroupSessionModel::SERVE_IN_NO,
            ] as $serveIn
        ) {

            $this->struct['tabs'][] = [
                'serveIn' => $serveIn,
                'tabName' => ChatGroupSessionModel::SERVE_IN_GROUP_TEXT[$serveIn],
                'count'   => ChatGroupSessionModel::query()
                                                  ->where('isNew', ChatGroupSessionModel::IS_NEW_YES)
                                                  ->where('serveIn', $serveIn)
                                                  ->count(),
            ];
        }

        $this->cmd = 'groupTabNum';

        return $this;
    }

    /**
     * 发送
     */
    public function send(): void
    {
        // MQTT send
        (new NsqPublisher(config('nsq.default.address')))
            ->pub(NsqEnum::TOPIC_MQTT_SEND, [
                'shopId'      => $this->shopId,
                'cmd'         => $this->cmd,
                'params'      => $this->struct,
                'connectType' => MqttEnum::MQTT_CLIENT_CONNECT_APP_WEB,
            ]);
    }
}
